package com.jinyou.utils.common;

//文件工具类

import com.jinyou.utils.oss.OssConfigConstants;
import com.jinyouapp.common.utils.image.FileStoryInfo;
import com.jinyouapp.common.utils.media.aliyun.AliOSSConfig;
import com.jinyouapp.common.utils.media.aliyun.AliyunMediaUtils;
import o2o.business.image.ImageBusiness;
import o2o.system.Common;
import o2o.system.data.SYS_CONFIG_PATH;

import org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

public class JYFileUtils {
    //文件夹
    //检测文件夹是否存在，不纯在创建
    public static boolean checkFilePath(String filePath) {
        File file = new File(filePath);
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            //不存在，创建
            file.mkdirs();
            return false;
        } else {
            //存在
            return true;
        }
    }

    //检测文件夹是否存在
    public static boolean checkFilePathExists(String filePath) {
        File file = new File(filePath);
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            //不存在，创建
            return false;
        } else {
            //存在
            return true;
        }
    }

    //获取文件夹路径
    public static String getFilePath(String path) {
        String filePath = path + "/" + DateUtils.getCurrentYearMonth();
        if (checkFilePath(filePath)) {
            return filePath;
        }
        return path;
    }

    //----------------------------------------文件
    //检测文件是否存在，不存在创建
    public static boolean checkFile(String fileFullPath) {
        File file = new File(fileFullPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        return true;
    }


    //检查文件是否存在
    public static boolean checkFileExists(String fileFullPath) {
        File file = new File(fileFullPath);
        if (!file.exists()) {
            return false;
        }

        return true;
    }

    //--------------------------------------获取文件

    //获取文件
    public static FilePath getFile(String folder, String fileName) {
        FilePath fp = new FilePath();
        String dbFilePath = folder;// + "/" + DateUtils.getCurrentYearMonth();
//        String filePath = Common.proImgPath + dbFilePath;
        String filePath = SYS_CONFIG_PATH.IMAGE_BASE_FILE + folder;
        fp.dbFileFullPath = dbFilePath + "/" + fileName;
        fp.fileFullPath = filePath + "/" + fileName;
        if (checkFilePath(filePath)) {
            File file = new File(fp.fileFullPath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
            fp.file = file;
            return fp;
        }
        return null;
    }


    //文件
    public static class FilePath {
        public String fileFullPath;//文件存储是实际全路径包含文件名
        public String dbFileFullPath;//数据库存储的路径
        public File file;//文件
    }


    public static void main(String[] args) {
        double deliveryPrice = 0d;
        Double distance = Geohash.distance(39.0287950, 88.1573070, 39.0202530, 88.1687920);//根据两点的经纬度计算距离
//                        Double km = distance / 1000;
        Double km = JYMathDoubleUtils.div(distance, 1000);
        System.out.println(km);
        if (km - 2.5 <= 0) {
            deliveryPrice = 5;
        } else {
            Double after = km - 1;
            Double round = Math.ceil(after);
            deliveryPrice = 2.5 + round;
        }

        System.out.println(deliveryPrice);
    }

    /**
     * 保存图片到本地环境
     *
     * @param folder
     * @param file
     * @return
     */
    public static String saveFileToLocal(String folder, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 获取文件类型
        FilePath fp = JYFileUtils.getFile(folder, getImageName(suffix));
        if (null == fp) {
            return null;
        }
        try {
            ImageBusiness.transferToServer(file, fp.file);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return null;
        }
        return fp.dbFileFullPath;
    }

    //获取图片名
    public static String getImageName(String suffix) {
        return Common.sdfDateNoh.format(new Date()) + ToolUtils.getNeedString(18) + "." + suffix;
    }

    public static FileStoryInfo saveFile2Oss(AliOSSConfig aliOSSConfig, MultipartFile avator, String folder, Boolean isCreateDateFile, boolean isAutoName) throws Exception {
        String url = AliyunMediaUtils.uploadFile2Oss(aliOSSConfig, avator, aliOSSConfig.getBucketName(), folder, isAutoName, isCreateDateFile, (String) null);
        FileStoryInfo info = new FileStoryInfo();
        info.setUrl(url);
        return info;
    }

    // 一乙文件保存分装
    public static FileStoryInfo saveFile2Oss(AliOSSConfig aliOSSConfig, MultipartFile avator, String folder) throws Exception {
        String url = AliyunMediaUtils.uploadFile2Oss(aliOSSConfig, avator, aliOSSConfig.getBucketName(), folder, false, false, (String) null);
        FileStoryInfo info = new FileStoryInfo();
        info.setUrl(url);
        return info;
    }

    public static String saveFile2Oss(String outPath) throws Exception {
        System.out.println("保存~~~~~" + OssConfigConstants.isUse);
        if (OssConfigConstants.isUse) {
            String folder = outPath;
            if (ValidateUtil.isNotNull(folder) && !folder.endsWith("/")) {
                folder = folder.substring(0, folder.lastIndexOf("/")) + "/";
                System.out.println(folder);
            }
            String name = outPath.substring(outPath.lastIndexOf("/") + 1);
            try (FileInputStream inputStream = new FileInputStream(new File(SYS_CONFIG_PATH.IMAGE_BASE_FILE + "/" + outPath));) {
                MultipartFile
                        avator = new MockMultipartFile(name, name, ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                FileStoryInfo fileStoryInfo = saveFile2Oss(getAliOssConfig(), avator, folder);
                String path = fileStoryInfo == null ? null : fileStoryInfo.getUrl();
                if (ValidateUtil.isNull(path)) {
                    return path;
                }
                if (ValidateUtil.isNotNull(OssConfigConstants.IMAGEBASEURL)) {
                    if (ValidateUtil.isNotNull(folder)) {
                        path = path.substring(path.indexOf(folder));
                    } else {
                        path = path.contains("/") ? path.substring(path.lastIndexOf("/")) : path;
                    }
                    path = OssConfigConstants.IMAGEBASEURL + path;
                }
                outPath = path;
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }
        return outPath;
    }

    private static AliOSSConfig getAliOssConfig() {
        return new AliOSSConfig(OssConfigConstants.ENDPOINT, OssConfigConstants.BUCKETNAME, OssConfigConstants.ACCESSKEYID, OssConfigConstants.ACCESSKEYSECRET);
    }

    // 微信退款证书上传文件
    public static String multipartFile(MultipartFile uploadFile, String path) throws Exception {
        if (null == uploadFile) {
            return "";
        }
        File file = new File(path);
        //判断上传文件目录是否存在
        if (!file.exists() && !file.isDirectory()) {
            //此目录不存在
            file.mkdirs();
        }

        String message = "";
        String fileName = uploadFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String filePath = path + "/" + new Date().getTime() + suffix;
        InputStream is = uploadFile.getInputStream();
        OutputStream os = new FileOutputStream(filePath);

        byte[] buffer = new byte[1024];
        int len = 0;

        while ((len = is.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        is.close();
        os.close();
        message = "文件上传成功";
        System.out.println(message);
        return filePath;
    }
}
